package com.gtw.memento.manyState;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;

public class BeanUtils {

    /**
     * 把Bean的全部属性放到HashMap中
     */
    public static HashMap<String, Object> backupProp(Object obj){
        HashMap<String, Object> result = new HashMap<String, Object>();

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for(PropertyDescriptor des : descriptors){
                //获取属性名称
                String fieldName = des.getName();
                Method getter = des.getReadMethod();
                //根et方法获取属性值
                Object fieldValue = getter.invoke(obj);
                if(!fieldName.equalsIgnoreCase("class")){
                    result.put(fieldName, fieldValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void restoreProp(Object bean, HashMap<String, Object> backupProp){
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for(PropertyDescriptor des : descriptors){
                //获取属性名称
                String fieldName = des.getName();
                if(backupProp.containsKey(fieldName)){
                    Method setter = des.getWriteMethod();
                    setter.invoke(bean, backupProp.get(fieldName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
